using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace OpenLS.Spreadsheet.UI.Internals
{
    class DefinedNamesCollectionView: INotifyCollectionChanged, IEnumerable<DefinedName>
    {
        private readonly ObservableCollection<DefinedName> _inner;

        public DefinedNamesCollectionView(ObservableCollection<DefinedName> inner)
        {
            _inner = inner;
            WeakEventHelper.AddWeakCollectionChanged(inner, OnCollectionChanged);
        }

        private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
        {
            var c = CollectionChanged;
            if (c != null)
                c(sender, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }

        public event NotifyCollectionChangedEventHandler CollectionChanged;
        public IEnumerator<DefinedName> GetEnumerator()
        {
            var result = new List<DefinedName>(_inner);
            result.Sort( (n1, n2) => n1.Name.CompareTo(n2.Name));
            return result.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}